package com.example.bid.config;

import com.daaao.bid.policy.redis.RedisIdTemplate;
import com.daaao.bid.policy.uid.impl.DefaultUidGenerator;
import org.apache.commons.lang.StringUtils;

/**
 * @author hao
 * @version 1.0
 * @date 2021/1/19 14:50
 */
public class Bid {

    public static long next(){
        try {
            DefaultUidGenerator defaultUidGenerator = ApplicationContextHolder.getBean("defaultUidGenerator", DefaultUidGenerator.class);
            return defaultUidGenerator.getUID();
        }catch (Exception e){
//            log.error("uid生成唯一ID失败，采用服务降级策略[redis]生成", e);
            RedisIdTemplate redisIdTemplate = ApplicationContextHolder.getBean("fullRedisIdTemplate", RedisIdTemplate.class);
            return Long.parseLong(redisIdTemplate.next());
        }
    }

    /**
     * 获取具备日期格式的ID
     * @param key 模块前缀，隔离作用
     * @return 具备日期格式的ID
     */
    public static String nextId(String key){
        RedisIdTemplate redisIdTemplate = ApplicationContextHolder.getBean("fullRedisIdTemplate", RedisIdTemplate.class);
        if(StringUtils.isEmpty(key)){
            return redisIdTemplate.next();
        }
        return redisIdTemplate.next(key);
    }

    /**
     * 获取具备日期格式的ID
     * @return 具备日期格式的ID
     */
    public static String nextId(){
        return nextId(null);
    }
}
